package com.edu.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.edu.entity.User;
import com.edu.service.impl.UserServerImpl;

/**
 * Servlet implementation class userLoginServlet
 */
@WebServlet(name = "loginDo", urlPatterns = { "/loginDo" })
public class userLoginServlet extends HttpServlet {

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		HttpSession session = request.getSession();
		UserServerImpl usi = new UserServerImpl();
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		User u = new User();
		u.setUsername(username);
		u.setPassword(password);
		System.out.println("u1:"+u.toString());
		User u2 = usi.userLogin(u);
		System.out.println("u2:"+u2.toString());
		String logInfo = "";
		if(u2.getUsername() != null && u2.getPassword() != null) {
			System.out.println("登录成功");
			session.setAttribute("logInUser", u2);
			Cookie usernameCookie = new Cookie("username", u2.getUsername());
			usernameCookie.setMaxAge(60 * 60 * 24 * 7);
			response.addCookie(usernameCookie);
			Cookie passwordCookie = new Cookie("password", u2.getPassword());
			passwordCookie.setMaxAge(60 * 60 * 24 * 7);
			response.addCookie(passwordCookie);
		}else {
			logInfo = "登录失败！用户名或密码错误！";
			System.out.println("登录失败");
			PrintWriter pw = response.getWriter();
			pw.print(logInfo);
			pw.flush();
		}
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
